package chinaums.web.controller;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import chinaums.common.anno.Log;
import chinaums.common.util.Crypt;
import chinaums.entity.CodeMsg;
import chinaums.service.IConfigureService;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

@Controller
@RequestMapping("/qrsms")
public class ConfigureController {
	private static final Logger logger = Logger.getLogger(ConfigureController.class);
	public static final String key = "31927HHdfsdfdsjdaD";//cookie加密密钥
	//private static String upload = "/weblogic/upload";
	private static String upload = "D:/123";
	private static String maxfilesize = "20971520";
	
	@Autowired
	private IConfigureService IConfigureService;
	
	/**
	 * 登陆页面显示
	 * @param request
	 * @param response
	 * @return
	 */
	@Log("登陆页面显示")
	@RequestMapping(value = "/login")
	public String gobackpage(HttpServletRequest request, HttpServletResponse response) {
		return "login";
	}
	
	/**
	 * 登陆接口
	 * @param request
	 * @param response
	 * @param username
	 * @param password
	 * @return
	 * @throws Exception
	 */
	@Log("登陆功能")
	@RequestMapping(value = "/dologin")
	@ResponseBody
	public String dologin(HttpServletRequest request, HttpServletResponse response,String username,String password) throws Exception {
		CodeMsg msg = new CodeMsg();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("username", username);
		map.put("password", Crypt.encryptMD5(password));
		long check = IConfigureService.dologin(map);
		if(check>0){
			msg.setCode("success");
			msg.setMsg("登陆成功");
			map.remove("password");
			msg.setValue(map);
			String jsonmap = JSON.toJSONString(msg);
			byte[] info = Crypt.encryptDES(jsonmap.getBytes("UTF-8"), key);
			String cookieStr = Base64.encodeBase64String(info);
	    	String cookieStrEncode = URLEncoder.encode(cookieStr,"UTF-8");
	    	Cookie cookie = new Cookie("li", cookieStrEncode);
	    	cookie.setPath("/");
	    	response.addCookie(cookie);
	    	return jsonmap;
		}else{
			msg.setCode("fail");
			msg.setMsg("登陆失败");
			String jsonmap = JSON.toJSONString(msg);
			return jsonmap;
		}
		
		
	}
	
	/**
	 * 任务上传页面显示
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	@Log("任务上传页面显示")
	@RequestMapping(value = "/uploadtask")
	public ModelAndView uploadtaskpage(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, Exception {
		ModelAndView mav = new ModelAndView("uploadtask");
		String jsonmap = getCardCheck(request);
		if(jsonmap==null || "".equals(jsonmap)){
			ModelAndView mav1 = new ModelAndView("redirect:/qrsms/login");
			return mav1;
		}
		
		
		return mav;
	}
	/**
	 * 任务列表页面显示
	 * @param request
	 * @param response
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	@Log("任务列表页面显示")
	@RequestMapping(value = "/tasklistpage")
	public ModelAndView tasklistpage(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, Exception {
		ModelAndView mav = new ModelAndView("tasklist");
		String jsonmap = getCardCheck(request);
		if(jsonmap==null || "".equals(jsonmap)){
			ModelAndView mav1 = new ModelAndView("redirect:/qrsms/login");
			return mav1;
		}
		
		
		return mav;
	}
	/**
	 * 任务列表ajax请求
	 * @param request
	 * @param response
	 * @param limit
	 * @param offset
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	@Log("任务列表ajax请求")
	@RequestMapping(value = "/tasklist")
	public void tasklist(HttpServletRequest request, HttpServletResponse response,Integer limit,Integer offset) throws UnsupportedEncodingException, Exception {
		List<Map<String,Object>> list = IConfigureService.gettasklist(limit,offset);
		long cnt = IConfigureService.gettasklistcnt(limit,offset);
		Map<String,Object> resultMap = new HashMap<String,Object>();
		resultMap.put("rows", list);
		resultMap.put("total", cnt);
		response.getWriter().print(JSON.toJSONString(resultMap));
	}
	
	
	/**
	 * 成功页面跳转
	 * @param request
	 * @param response
	 * @param msg
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@Log("成功页面跳转")
	@RequestMapping(value = "/successpage")
	public ModelAndView successpage(HttpServletRequest request, HttpServletResponse response,String msg) throws UnsupportedEncodingException {
		response.setCharacterEncoding("UTF-8");
		ModelAndView mav = new ModelAndView("successpage");
		
		
		mav.addObject("msg", msg);
		return mav;
	}
	/**
	 * 失败页面跳转
	 * @param request
	 * @param response
	 * @param msg
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@Log("失败页面跳转")
	@RequestMapping(value = "/failpage")
	public ModelAndView failpage(HttpServletRequest request, HttpServletResponse response,String msg) throws UnsupportedEncodingException {
		response.setCharacterEncoding("UTF-8");
		ModelAndView mav = new ModelAndView("failpage");
		
		
		mav.addObject("msg", msg);
		return mav;
	}
	
	
	/**
	 * 上传文件
	 * @param response
	 * @param request
	 * @param attr
	 * @param fileList
	 * @throws Exception 
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public void uploadFile(HttpServletResponse response, HttpServletRequest request,RedirectAttributes attr,  @RequestParam("uploadFile") MultipartFile[] fileList) throws UnsupportedEncodingException, Exception {
		CodeMsg msg1 = new CodeMsg();
		boolean flg = true;
		String msg = "";
		Map<String, Object> resMap = new HashMap<String,Object>();
		String jsonmap = getCardCheck(request);//得到cookie里的创建人
		Map<String, Object> cookmap = JSON.parseObject(jsonmap,new TypeReference<Map<String, Object>>(){});
		String loginuser = (String) cookmap.get("username");
		if(fileList.length>1){//通用多文件上传方法，这里限定为1个文件上传
			try {
				msg1.setCode("fail");
				msg1.setMsg("不能上传多个文件");
				response.getWriter().print(JSON.toJSONString(msg1));
				return;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			
		}
		
		
			msg = checkFile(fileList[0]);//检查文件
			if (null == msg || !"Y".equals(msg)) {
				attr.addFlashAttribute("msg", msg);
				
				msg1.setCode("fail");
				msg1.setMsg(msg);
				//msg1.setValue(resMap);
				flg = false;
				response.getWriter().print(JSON.toJSONString(msg1));
				return;
			}
		
		if (flg) {
			
				String resString = fileUpload(fileList[0], fileList[0].getOriginalFilename(),upload);//上传文件，返回文件上传后保存的路径
				
					msg1 = IConfigureService.insertExceltoDateBase(resString,loginuser);//将excl导入数据库
				
			
					response.getWriter().print(JSON.toJSONString(msg1));
			
		}

		
	}
	
	/**
	 * 检查上传文件
	 * @param file
	 * @return
	 */
	private String checkFile(MultipartFile file) {
		try {
			CodeMsg msg = new CodeMsg();
			String fileName = file.getOriginalFilename();//得到上传的文件名
			String message = "Y";
			int flieMaxSize = Integer.valueOf(maxfilesize);
			if (file == null || file.isEmpty()) {
				message = "对不起,你上传的文件不存在!!!";
			}
			if (!fileName.toLowerCase().endsWith(".xls") && !fileName.toLowerCase().endsWith(".xlsx")) {
				message = "对不起,你上传的文件格式不允许!!!";
			}
			if (file.getSize() > flieMaxSize) {
				message = "上传文件超过最大上传大小20M,请调整后重新上传。";
			}
			return message;
		} catch (Exception e) {
			
			return "操作失败！ 原因：" + e.toString();
		}
	}
	
	
	
	
	
	/**
	 * 文件上传功能
	 * @param f
	 * @param targetName
	 * @param uploadType
	 * @return
	 */
	public static String fileUpload(MultipartFile f,String targetName,String uploadType) {
    	String message = "";
        try {
        
        	String time=System.currentTimeMillis() + "";//获取系统当前时间戳
        	targetName=time+targetName;//文件名
            byte[] fileArray=getFileContent(f);//文件转换成2进制数据流
            doUploadFile(fileArray,targetName,time);//文件上传方法
            message = uploadType+"/"+targetName;//返回路径名+文件名
        } catch (Exception e) {
            e.printStackTrace();
            message = "0";
        }
        return message;
    }
	/**
	 * 文件大小判断
	 * @param f
	 * @return
	 * @throws IOException
	 */
	public static byte[] getFileContent(MultipartFile f) throws IOException {  
        long fileSize = f.getSize();//文件大小
        if (fileSize > Integer.MAX_VALUE) {  
            System.out.println("file too big...");  
            return null;
        }  
        return f.getBytes();  
    }  
	/**
	 * 文件buffer上传到服务器，并关闭
	 * @param buffer
	 * @param targetName
	 * @param time
	 * @throws Exception
	 */
	 public static void doUploadFile(byte[] buffer, String targetName, String time) throws Exception {
	     FileOutputStream out = new FileOutputStream(upload+"/"+targetName);
	     out.write(buffer);
	     out.close();
	 }
	/**
	 * cookie获取
	 * @param request
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws Exception
	 */
	 public static String getCardCheck(HttpServletRequest request) throws UnsupportedEncodingException, Exception{
    	
    	Cookie[] cookies = request.getCookies();  
        if (cookies != null) {  
            for (Cookie cookie : cookies) {  
                if (("li").equals(cookie.getName())) {  
                	String cookieStr =cookie.getValue();
                	String uJsonDecode = URLDecoder.decode(cookieStr,"UTF-8");
                	//byte[] ubyte = uJsonDecode.getBytes("UTF-8");
                	byte[] ubyte = Base64.decodeBase64(uJsonDecode);
        			String verifycode = new String(Crypt.decryptDES(ubyte,key),"UTF-8");
        			return verifycode;
                }  
            }  
        }  
        return null;
    }
	@RequestMapping("/cookiers")
	public void getcookier(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException, Exception{
		String jsonmap = getCardCheck(request);//得到cookie里的创建人
		Map<String, Object> cookmap = JSON.parseObject(jsonmap,new TypeReference<Map<String, Object>>(){});
		Map<String,Object> map1 = new HashMap<String,Object>();
		map1 = (Map<String, Object>) cookmap.get("value");
		String loginuser = (String) map1.get("username");
		request.setAttribute("loginuser", loginuser);
		System.out.println("名字是："+loginuser);
		
		response.getWriter().print(JSON.toJSONString(loginuser));
	}
	@RequestMapping("/cancel")
	public String cancelCookier(HttpServletRequest request, HttpServletResponse response){
		Cookie newCookie=new Cookie("li",null); //要删除名称为li的Cookie
		newCookie.setMaxAge(0); //立即删除型
		newCookie.setPath("/"); //项目所有目录均有效，这句很关键，否则不敢保证删除
		response.addCookie(newCookie); //重新写入，将覆盖之前的
		return "redirect:/qrsms/login";
	}
	
	
	
	
	
	
	
}
